package com.qf.hospital.realm;

import com.qf.hospital.entity.User;
import com.qf.hospital.enums.HospitalErrorEnums;
import com.qf.hospital.exception.HospitalException;
import com.qf.hospital.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Administrator
 * @version V1.0
 * @Project hospital
 * @Package com.qf.hospital.realm
 * @Description: ${TODO}
 * @Date 2021/10/15 11:26
 */
public class HospitalRealm extends AuthorizingRealm {
    public static final int HASH_ITERATIONS = 1024;


    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(HASH_ITERATIONS);
        this.setCredentialsMatcher(matcher);
    }
    @Autowired
    private UserService userService;

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1. 获取用户名
        String loginName = (String) authenticationToken.getPrincipal();
        //2. 根据用户名查询
        User user = userService.findByName(loginName);
        //3. 判断查询结果
        if (user == null){
            throw new HospitalException(HospitalErrorEnums.USERNAME_PASSWORD_ERROR);
        }
        //4. 封装返回结果
        SimpleAuthenticationInfo Info = new SimpleAuthenticationInfo(user,user.getPwd(),"HospitalRealm");
        //5. 设置盐
        Info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        //6.返回
        return Info;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
